package com.winbomb.kingcard.base.anim.impl;

import com.winbomb.kingcard.ICard;
import com.winbomb.kingcard.IGameLogic;
import com.winbomb.kingcard.IPlayer;
import com.winbomb.kingcard.Pos;
import com.winbomb.kingcard.base.anim.IPlayable;
import com.winbomb.kingcard.screens.util.Render;

public class MovingCardsAnim implements IPlayable {

	public static final int STEP = 2;

	private int fx, fy, tx, ty;
	private int cx, cy;
	private ICard[] cards;
	private boolean isOpened;
	private IPlayer sourcePlayer;
	private IPlayer targetPlayer;

	public MovingCardsAnim(IGameLogic game) {
	}

	@Override
	public boolean play(float dt) {

		if (cx == tx && cy == ty) {
			if (targetPlayer.isAlive()) {
				targetPlayer.takeback(cards);
			} else {
				targetPlayer.revitalize(sourcePlayer, cards);
			}

			return true;
		}

		if (isOpened) {
			for (int i = 0; i < cards.length; i++) {
				Render.drawCard(cards[i], cx + i * 30, cy);
			}
		} else {
			for (int i = 0; i < cards.length; i++) {
				Render.drawCardBack(cx + i * 30, cy);
			}
		}

		// 更新位置, 先沿着X轴方向移动
		if (cx != tx) {
			cx += (tx - fx >= 0) ? STEP : 0 - STEP;
			if (Math.abs(cx - fx) >= Math.abs(tx - fx)) {
				cx = tx;
			}

		}

		if (cy != ty) {
			cy += (ty - fy >= 0) ? STEP : 0 - STEP;
			if (Math.abs(cy - fy) >= Math.abs(ty - fy)) {
				cy = ty;
			}
		}

		return false;
	}

	public void reset() {
		this.fx = 0;
		this.fy = 0;
		this.cx = 0;
		this.cy = 0;
		this.tx = 0;
		this.ty = 0;
		this.cards = null;
		this.isOpened = false;
		this.sourcePlayer = null;
		this.targetPlayer = null;
	}

	public void setStartPos(Pos startPos) {
		this.fx = startPos.x + 4;
		this.fy = startPos.y + 4;
		this.cx = fx;
		this.cy = fy;

	}

	public void setTargetPos(Pos targetPos) {
		this.tx = targetPos.x + 4;
		this.ty = targetPos.y + 4;
	}

	public void setCards(ICard[] cards) {
		this.cards = cards;
	}

	public void setOpened(boolean isOpened) {
		this.isOpened = isOpened;
	}

	public void setTargetPlayer(IPlayer targetPlayer) {
		this.targetPlayer = targetPlayer;
	}

	public void setSourcePlayer(IPlayer sourcePlayer) {
		this.sourcePlayer = sourcePlayer;
	}

}
